package com.analy.service.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.analy.core.AnalyThread;
import com.analy.service.WorkService;
import com.common.cache.Cache;
import com.common.vo.SnatchItem;
import com.common.vo.SnatchTask;

@Service
public class WorkServiceImpl implements WorkService {

	protected Logger logger = Logger.getLogger(WorkServiceImpl.class);

	/*private ExecutorService snatchExecutorService = Executors
			.newCachedThreadPool();// 抓取线程
*/
	private ConcurrentMap<String, ConcurrentHashMap<String,AnalyThread>> analyTaskMap = new ConcurrentHashMap<String, ConcurrentHashMap<String,AnalyThread>>();// 每个抓取线程版本号内存队列

	@Autowired
	private Cache redisCache;
	
	@Override
	public int analyTask(SnatchTask snatchTask,SnatchItem snatchItem) {
		ConcurrentHashMap<String,AnalyThread> webSnatchs = analyTaskMap.get(snatchTask.getWebCode());
		if(null == webSnatchs){
			webSnatchs = new ConcurrentHashMap<String,AnalyThread>();
			analyTaskMap.put(snatchTask.getWebCode(), webSnatchs);
		}
		
		if (webSnatchs.get(snatchTask.getTaskCode()) != null) {
			return -1;
		}
		
		if(1 == snatchTask.getValid()){
			AnalyThread snatchThread = new AnalyThread();
			snatchThread.init(snatchTask,snatchItem,redisCache);
			snatchThread.start();
			webSnatchs.put(snatchTask.getTaskCode(), snatchThread);
			snatchItem.setDescribe("解析任务启动!");
		}else{
			AnalyThread snatchThread = webSnatchs.get(snatchTask.getTaskCode());
			if(null != snatchThread){
				snatchThread.destroy();
				webSnatchs.remove(snatchTask.getTaskCode());
			}
		}
		return 1;
	}

	

	
}
